package com.xie.smfs.item;

import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.xie.smfs.entity.GhostEntity;
import com.xie.smfs.registry.ModEffects;
import com.xie.smfs.registry.ModItems;
import java.util.List;
import java.util.UUID;
import net.minecraft.entity.Entity;  // 正确导入

public class RedGhostCandleItem extends Item {
    // 基础耐久值
    private static final int BASE_DURABILITY = 100;
    // 距离阈值
    private static final double DISTANCE_THRESHOLD = 20.0;

    public RedGhostCandleItem(Settings settings) {
        super(settings.maxDamage(BASE_DURABILITY));
    }

    @Override
    public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
        super.inventoryTick(stack, world, entity, slot, selected); // 调用父类逻辑
        if (!world.isClient && entity instanceof PlayerEntity player) {
            // 检查玩家是否手持该物品
            if (player.getMainHandStack() == stack || player.getOffHandStack() == stack) {
                checkAndConsumeDurability(stack, player);
            }
        }
    }

    private void checkAndConsumeDurability(ItemStack stack, PlayerEntity player) {
        World world = player.getWorld();
        // 获取附近的幽灵实体
        List<GhostEntity> nearbyGhosts = world.getEntitiesByClass(
            GhostEntity.class,
            player.getBoundingBox().expand(DISTANCE_THRESHOLD),
            ghost -> true
        );

        if (!nearbyGhosts.isEmpty()) {
            float maxConsumptionRate = 0.0f;
            for (GhostEntity ghost : nearbyGhosts) {
                double distance = player.squaredDistanceTo(ghost);
                if (distance <= DISTANCE_THRESHOLD * DISTANCE_THRESHOLD) {
                    double actualDistance = Math.sqrt(distance);
                    float consumptionRate = calculateConsumptionRate(actualDistance, ghost.getTerrorLevel());
                    if (consumptionRate > maxConsumptionRate) {
                        maxConsumptionRate = consumptionRate;
                    }
                }
            }

            // 根据最大消耗速率决定是否消耗耐久
            if (maxConsumptionRate > 0 && world.random.nextFloat() < maxConsumptionRate) {
                stack.damage(1, player, p -> p.sendToolBreakStatus(p.getActiveHand()));
            }
        }
    }

    private float calculateConsumptionRate(double actualDistance, char terrorLevel) {
        // 距离因子
        float distanceFactor = actualDistance < DISTANCE_THRESHOLD ? 
            (float)(1.0 - (actualDistance / DISTANCE_THRESHOLD)) : 0.0f;

        // 等级因子（等级越高消耗越快）
        float levelFactor = getLevelFactor(terrorLevel);

        // 基础消耗速率（每tick的概率）
        float baseRate = 0.1f; // 提高基础消耗概率


        // 综合计算消耗速率（最高不超过0.8）
        return Math.min(baseRate * distanceFactor * levelFactor, 0.8f);
    }

    private float getLevelFactor(char level) {
        return switch (level) {
            case 'S' -> 2.0f;
            case 'A' -> 1.5f;
            case 'B' -> 1.2f;
            case 'C' -> 1.0f;
            case 'D' -> 0.8f;
            default -> 1.0f;
        };
    }

    // 判断玩家是否手持鬼烛
    public static boolean isHoldingCandle(PlayerEntity player) {
        return player.getMainHandStack().isOf(ModItems.RED_GHOST_CANDLE) || 
               player.getOffHandStack().isOf(ModItems.RED_GHOST_CANDLE);
    }
}